package com.platform.service.impl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.platform.annotation.SysLog;
import com.platform.common.ServerResponse;
import com.platform.dao.RoleMapper;
import com.platform.pojo.Role;
import com.platform.service.IRoleService;
import com.platform.util.NumberUtil;
import com.platform.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 角色服务层
 */
@Service("iRoleService")
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;


    @SysLog("新增角色")
    public ServerResponse<String> insert(Map map){
        Role role = new Role();
        role.setRoleName(StringUtil.valueOfString(map.get("roleName")));
        role.setRoleCode(StringUtil.valueOfString(map.get("roleCode")));
        //查询角色编码是否存在
        int countNums = roleMapper.countNumsByRoleCode(role.getRoleCode());
        if(countNums > 0){
            return ServerResponse.createByErrorMessage("角色编码已存在");
        }
        int countResult = roleMapper.insert(role);
        if(countResult > 0){
            return ServerResponse.createBySuccessMessage("操作成功");
        }
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @SysLog("删除角色")
    public ServerResponse<String> del(Integer id){
        int countResult = roleMapper.deleteByPrimaryKey(id);
        if(countResult > 0){
            return ServerResponse.createBySuccessMessage("操作成功");
        }
        return ServerResponse.createByErrorMessage("操作失败");
    }

    @SysLog("查询所有角色")
    public ServerResponse<PageInfo> selectByParam(Map param){
        int pageNo = NumberUtil.safeToNumber(param.get("pageNo"),1);
        int pageSize = NumberUtil.safeToNumber(param.get("pageSize"),10);
        String orderBy = StringUtil.valueOfString(param.get("orderBy"));
        //分页组件
        PageHelper.startPage(pageNo,pageSize,orderBy);
        List<Map> roleList = roleMapper.selectByParam(param);
        PageInfo pageInfo = new PageInfo(roleList);
        pageInfo.setList(roleList);//返回分页组件类
        return ServerResponse.createBySuccess("查询成功",pageInfo);
    }

    @SysLog("更新角色信息")
    public ServerResponse<String> update(Map map){
        Integer id = NumberUtil.safeToNumber(map.get("id"));
        Role role = roleMapper.selectByPrimaryKey(id);
        if(role == null){
            return ServerResponse.createByErrorMessage("参数错误");
        }
        role.setRoleCode(StringUtil.valueOfString(map.get("roleCode")));
        role.setRoleName(StringUtil.valueOfString(map.get("roleName")));
        role.setUpdateTime(new Date());
        if(roleMapper.updateByPrimaryKey(role) > 0){
            return ServerResponse.createBySuccessMessage("保存成功");
        }
        return ServerResponse.createByErrorMessage("保存失败");
    }
}
